package org.javabasics.thread.communication;

import java.util.Objects;

/**
 * Created by LUOLIANG on 2016/10/9.
 */
public class Account {
    //封装账户编号，账户余额两个成员变量
    private String accountNo;
    private double balance;
    //标识当前账户是否已存款
    private boolean flag = false;

    public Account() {
    }

    public Account(String accountNo, double balance) {
        this.accountNo = accountNo;
        this.balance = balance;
    }

    public String getAccountNo() {
        return accountNo;
    }

    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    public double getBalance() {
        return balance;
    }

    /**
     * 取钱
     */
    public synchronized void draw(double drawAmount) {
        try {
            //为false表明没有人存钱进去，取钱方法阻塞
            if (!flag) {
                wait();
            } else {
                System.out.println(Thread.currentThread().getName() + "执行取钱操作,金额为：" + drawAmount);
                balance -= drawAmount;
                System.out.println(Thread.currentThread().getName() + "取钱后，余额为: " + balance);
                flag = false;
                notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 存钱
     *
     * @param depositAmount
     */
    public synchronized void deposit(double depositAmount) {

        try {
            if (flag) {
                wait();
            } else {
                System.out.println(Thread.currentThread().getName() + "执行存钱操作，金额为：" + depositAmount);
                balance += depositAmount;
                System.out.println(Thread.currentThread().getName() + "存钱后，余额为：" + balance);
                flag = true;
                notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Account account = (Account) o;
        return Double.compare(account.balance, balance) == 0 &&
                Objects.equals(accountNo, account.accountNo);
    }

    @Override
    public int hashCode() {
        return Objects.hash(accountNo, balance);
    }
}
